
package com.bei_en.teacher.management.shiro;

import java.util.concurrent.atomic.AtomicInteger;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;

/**
 * <p>User: Zhang Kaitao
 * <p>Date: 14-1-28
 * <p>Version: 1.0
 */
public class LimitRetryHashedMatcherEhCache extends HashedCredentialsMatcher {

    Logger log = Logger.getLogger(this.getClass());

    private Ehcache passwordRetryCache;

    public LimitRetryHashedMatcherEhCache(CacheManager cacheManager) {

	passwordRetryCache = cacheManager.getCache("my_passwordRetryCache");
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

	String username = (String) token.getPrincipal();
	// retry count + 1
	Element element = passwordRetryCache.get(username);
	if (element==null) {
	    element = new Element(username, new AtomicInteger(0));
	    passwordRetryCache.put(element);
	    log.warn(username+":尝试登录次数=0");
	}
	AtomicInteger retryCount = (AtomicInteger) element.getObjectValue();
	if (retryCount.incrementAndGet()>5) {
	    // if retry count > 5 throw
	    log.warn(username+":尝试登录次数大于5");
	    throw new ExcessiveAttemptsException();
	}

	boolean matches = super.doCredentialsMatch(token, info);
	if (matches) {
	    // clear retry count
	    passwordRetryCache.remove(username);
	}
	return matches;
    }
}
